from django.shortcuts import render
from rest_framework.permissions import IsAuthenticated
from rest_framework.views import APIView
from django_redis import get_redis_connection
import decimal
from rest_framework.response import Response
from rest_framework.generics import CreateAPIView

from goods.models import SKU
from .serializers import OrderGoodsSerializer, CommitOrderSerializer


# Create your views here.

#     url(r'^orders/settlement/$', views.OrderSettlementView.as_view()),
class OrderSettlementView(APIView):
    """
    订单结算
    """
    permission_classes = [IsAuthenticated]

    def get(self, request):

        user = request.user
        redis_con = get_redis_connection("carts")
        cart_dict = redis_con.hgetall("cart_%s" % user.id)
        cart_selected  = redis_con.smembers("selected_%s" % user.id)

        order_dict = {}
        for sku_id in cart_selected:
            order_dict[int(sku_id)] = int(cart_dict[sku_id])

        skus = SKU.objects.filter(id__in=order_dict.keys())
        for sku in skus:
            sku.count = order_dict[sku.id]
        # 这里的运费可以自定义,现在是写死了
        freight = decimal.Decimal('10.00')

        serializer = OrderGoodsSerializer({"freight": freight, "skus": skus})
        return Response(serializer.data)


class CommitOrderView(CreateAPIView):
    permission_classes = [IsAuthenticated]
    serializer_class = CommitOrderSerializer

